import argparse, os, re, subprocess, shutil
from pathlib import Path
import yaml

WS = Path(__file__).resolve().parents[1]
SRC = WS / "src"

ALL_PACKAGES = ["ts-common", "ts-comms", "ts-mock"]  # 🔒 写死的包名列表

def parse_args():
    p = argparse.ArgumentParser(prog="conan install")
    p.add_argument(
        "-p",
        "--package",
        type=str,
        required=True,
        nargs="+",
        help="创建的package名: eg(ts-common, ts-comms)"
    )

    return p.parse_args()


def main():
    # parse args
    args = parse_args()
    
    pkgs= args.package
    print(f"=== Packages: {', '.join(pkgs)}")


    for pkg in pkgs:
        
        base_dir = SRC/ pkg
        base_dir.mkdir(parents=True, exist_ok=True)
        
        package_xml = f"""<?xml version="1.0"?>
<package format="3">
  <name>{pkg}</name>
  <version>0.1.0</version>
  <description>{pkg} package</description>
  <maintainer email="you@example.com">You</maintainer>
  <license>MIT</license>
  <buildtool_depend>cmake</buildtool_depend>
</package>"""

        with open(os.path.join(base_dir, "package.xml"), "w") as f:
            f.write(package_xml)

         # 创建 CMakeLists.txt
        cmakelists = f"""cmake_minimum_required(VERSION 3.20)
project({pkg} LANGUAGES CXX)

# 必须在 project() 之后设置
set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE BOOL "Enable compile commands export" FORCE)

# 自动检测构建类型
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Build type" FORCE)
endif()

# 设置 Conan 生成文件路径
set(CONAN_GENERATORS_DIR "${{CMAKE_CURRENT_SOURCE_DIR}}/conan/${{CMAKE_BUILD_TYPE}}")

# 包含 Conan 工具链文件
if(EXISTS "${{CONAN_GENERATORS_DIR}}/conan_toolchain.cmake")
    include("${{CONAN_GENERATORS_DIR}}/conan_toolchain.cmake")
    message(STATUS "Using Conan toolchain: ${{CONAN_GENERATORS_DIR}}/conan_toolchain.cmake")
else()
    message(WARNING "Conan toolchain file not found at ${{CONAN_GENERATORS_DIR}}/conan_toolchain.cmake")
endif()

# 添加 Conan 生成目录到搜索路径
list(APPEND CMAKE_PREFIX_PATH "${{CONAN_GENERATORS_DIR}}")
set(CMAKE_MODULE_PATH "${{CONAN_GENERATORS_DIR}}" ${{CMAKE_MODULE_PATH}})


add_executable({pkg} src/main.cpp)
target_compile_features({pkg} PRIVATE cxx_std_17)

install(TARGETS ${pkg} RUNTIME DESTINATION bin)
"""

        with open(os.path.join(base_dir, "CMakeLists.txt"), "w") as f:
            f.write(cmakelists)
    
        
        src_dir = base_dir/ "src"
        src_dir.mkdir(parents=True, exist_ok=True)
        # 创建 main.cpp
        main_cpp = f"""#include <iostream>
int main() {{
    std::cout << "Hello from {pkg}!" << std::endl;
    return 0;
}}"""

        with open(os.path.join(src_dir, "main.cpp"), "w") as f:
            f.write(main_cpp)


        conan_dir = base_dir / "conan"
        conan_dir.mkdir(parents=True, exist_ok=True)

        conanfile_txt = """[requires]

[generators]
CMakeDeps
CMakeToolchain
"""

        with open(os.path.join(conan_dir, "conanfile.txt"), "w") as f:
            f.write(conanfile_txt)
        print("✅ 完成，可以 colcon build 了")


if __name__ == "__main__":
    main()
